package com.miage.pki.interceptor;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.miage.pki.interceptor.Menu.MenuItem;

public class MenuInterceptor extends HandlerInterceptorAdapter {

	public MenuInterceptor() {}

	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) {
	    
	    String role = SecurityContextHolder.getContext().getAuthentication().getAuthorities().toString();
	    
	    ArrayList<MenuItem> menu;
	    if(role.equals("[ROLE_ADMIN]")){
	        menu = (ArrayList<MenuItem>) Menu.getAdminMenu();
	    }else if(role.equals("[ROLE_CLIENT]")){
            menu = (ArrayList<MenuItem>) Menu.getClientMenu();
        }else if(role.equals("[]")){
            menu = (ArrayList<MenuItem>) Menu.getSimpleUserMenu();
        }else{
            menu = (ArrayList<MenuItem>) Menu.getNotLoggedMenu();
        }
	    
	    String currentPath = request.getRequestURI().substring(request.getContextPath().length()+1);
	    
	    for(MenuItem m : menu){
	        if(m.getLink().substring(0, 4).equals(currentPath.substring(0, 4))){
	            m.setCurrent(true);
	            break;
	        }
	    }
		
		modelAndView.addObject("menu", menu);
	}
}